package com.vj.router.client.grpc;

import com.vj.router.common.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class GrpcDeviceGatewayClient {

    private final ManagedChannel channel;
    private final RouterDeviceGatewayServiceGrpc.RouterDeviceGatewayServiceBlockingStub blockingStub;

    // 构造方法，初始化 gRPC 通道和 stub
    public GrpcDeviceGatewayClient(String target) {
        this.channel = ManagedChannelBuilder.forTarget(target)
                .usePlaintext() // 明文传输，适用于未开启 TLS 的服务
                .build();
        this.blockingStub = RouterDeviceGatewayServiceGrpc.newBlockingStub(channel);
    }

    // 注册路由
    public String registerRoute(String deviceId, String gatewayId) {
        RegisterDeviceGatewayRouteRequest request = RegisterDeviceGatewayRouteRequest.newBuilder()
                .setDeviceId(deviceId)
                .setGatewayId(gatewayId)
                .build();

        RegisterDeviceGatewayRouteResponse response = blockingStub.registerRoute(request);
        return response.getMessage();
    }

    // 获取路由
    public String getRoute(String deviceId) {
        GetDeviceGatewayRouteRequest request = GetDeviceGatewayRouteRequest.newBuilder()
                .setDeviceId(deviceId)
                .build();

        GetDeviceGatewayRouteResponse response = blockingStub.getRoute(request);
        return response.getGatewayId();
    }

    // 注销路由
    public String unregisterRoute(String deviceId) {
        UnregisterDeviceGatewayRouteRequest request = UnregisterDeviceGatewayRouteRequest.newBuilder()
                .setDeviceId(deviceId)
                .build();

        UnregisterDeviceGatewayRouteResponse response = blockingStub.unregisterRoute(request);
        return response.getMessage();
    }

    // 关闭通道
    public void shutdown() {
        if (!channel.isShutdown()) {
            channel.shutdown();
        }
    }
}
